<?php
/* Map Outlet
 * Google Map API 3
 * Please change your key to meet your server
 * by Tubagus Rafi Kusuma
 */  
 //Rafi Here
        
$terr = "";
if($this->input->post("user")) {
    $v = 1;
    $terr = "";
    foreach($this->input->post("user") as $x) {
        if($v <> 1) {
            $terr .= ",";
        }
        $terr .= $x;
        //$territory_array[] = $x;
        $v++;
    }
//echo $terr;
////$ter_array = array_unique($territory_array);
}
 
  
?>
<link rel="stylesheet" type="text/css" href="<?=base_url()?>file/js/easyui/themes/default/easyui.css" />
<link rel="stylesheet" type="text/css" href="<?=base_url()?>file/js/easyui/themes/icon.css" />
<script type="text/javascript" src="<?=base_url()?>file/js/easyui/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="<?=base_url()?>file/js/easyui/jquery.easyui.min.js"></script>
<!--<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC0JhNTyjMpdmUPMDYWIVuE57dUIHZH1SU&sensor=true"></script>-->
<script type="text/javascript" src="<?=$api?>"></script>
<script>
$("#li").hide();
//test
 
</script>
<script type="text/javascript">
  
    
     
</script>


<div class="box">
     <!-- box / title -->
        <div class="title">
                <h5>SIG > Peta Outlet</h5>                
        </div>
        
        <form id="form" action="<?=$_SERVER['PHP_SELF']?>" method="post">
                <div class="form">
                        <div class="fields">
                            <!--    
                            <div class="field">
                                        <div class="label">
                                                <label for="user">Teritori:</label>
                                        </div>
                                        <div class="input">
                                                <input id="cc" name="territory" class="easyui-combotree" url="<?= base_url()?>index.php/gis/territory_json0" value="<?= $this->input->post('territory') ? $this->input->post('territory') : 1 ?>" required="true" style="width:200px;">                                                
                                        </div>
                                </div>
                                -->          
                            <div class="field">
                                        <div class="label">
                                                <label for="user">ID Outlet:</label>
                                        </div>
                                        <div class="input">
                                                <input name="outlet_id" value="<?= $this->input->post('outlet_id') ? $this->input->post('outlet_id') : '' ?>" style="width:200px;">                                                
                                        </div>
                                </div> 
                            <div class="field">
                                        <div class="label">
                                                <label for="user">Nama Outlet:</label>
                                        </div>
                                        <div class="input">
                                                <input name="outlet_name" value="<?= $this->input->post('outlet_name') ? $this->input->post('outlet_name') : '' ?>" style="width:200px;">                                                
                                        </div>
                                </div> 
                            <div class="buttons">
                                        <input type="submit" name="submit" value="Cari Outlet" />                                     
                                </div>
                        </div>
                </div>
        </form>
        <script type="text/javascript">
            (function() {
//                // Info Box Callbacks
//		function ibCallbacks(){
//			$(".tweets").each(function(){
//				var username = $(this).attr("title");
//				$(this).empty().tweet({username: username,count: 3,loading_text: "loading tweets...",template: "{text}  {time}"});
//			});
//			
//			$(".iw-body").myTabs({hidewhat:".iw-body-main",controller:".iw-body-tabs a"});
//		}
                
                window.onload = function() {
                
                // Creating a map
                //by donny
                var zl=18;
                var got=false;
                var lat=[];
                var lng=[];
                <?
                        /* yufan Mencoba */
                        
                        /*
                        $usr=$this->input->post("user");
                        if ($usr!=null)
                        {
                            $data = $this->mqis->getMapOutlet($this->input->post('outlet_id'));
                            
                            $x = 0;
                            foreach ($data as $item)
                            {
                                echo  "lat.push(".$item->lat.");";
                                echo  "lng.push(".$item->lon.");";        
                            }
                            
                        }*/
                        
                        $x = 0;
                        foreach($hasil as $v) {
                            if($v->lat <> "" || $v->lon <> "" || $v->lat<>0 || $v->lon <>0) {
                            echo  "lat.push(".$v->lat.");";
                            echo  "lng.push(".$v->lon.");";
                            }
                        }    
                    ?>
                    
                    
                    
               function getmax(aray){
                    var max=aray[0];
                    for (i =1; i<aray.length;i++){
                        if (max<aray[i]){
                            max=aray[i]
                        }
                        
                    }
                    return max;
                }
                
                function getmin(aray){
                    var max=aray[0];
                    for (i =1; i<aray.length;i++){
                        if (max>aray[i]){
                            max=aray[i]
                        }
                        
                    }
                    return max;
                }
                        

                
				var maxlng=getmax(lng);
				var minlng=getmin(lng);
				var maxlat=getmax(lat);
				var minlat=getmin(lat);
                
               //alert ('maxlng='+maxlng+'\nmaxlat='+maxlat+'\nminlng='+minlng+'\nminlat='+minlat);

                        //alert (maxlng + "-" + minlng + "-" + maxlat + "-" + minlat );
               			var clat=minlat + ((maxlat-minlat)/2);
				        var clng=minlng + ((maxlng-minlng)/2);
                
                //donny adiwilaga was here
                if (maxlng==null || maxlat==null || minlng==null || minlat==null){got=true;zl=5;clat=-1.9112665350965847;clng=117.7294921875}else{got=false;}
                
                var options = {
                zoom: zl,
                center: new google.maps.LatLng(clat,clng),
                mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                
                //var map = new google.maps.Map(document.getElementById('map'), options);
                // Creating an array that will contain the coordinates 
                

                
/**
 *                 var options = {
 *                 zoom: 5,
 *                 center: new google.maps.LatLng(-1.9112665350965847,117.7294921875),
 *                 mapTypeId: google.maps.MapTypeId.ROADMAP
 *                 };
 */
                
                var map = new google.maps.Map(document.getElementById('map'), options);
                var myInfowindow = new google.maps.InfoWindow();
                
                //-----------------------
                
                
                
                
                
                
                
                
                var info = [];
                                        
                var places = [];
                // Adding a LatLng object for each city
                <?php
                if($hasil != null) {
                    $x = 0;
                    foreach($hasil as $v) {
                        if($v->lat <> "" || $v->lon <> "") {
                            echo "places.push(new google.maps.LatLng(".$v->lat.",".$v->lon."));";
                            echo "info[$x] = \"<b>Nama Outlet : ".pg_escape_string($v->outlet_name)."</b><br />Alamat : ".pg_escape_string($v->address)."<br />Kota : ".pg_escape_string($v->city)."<br />Kodepos : $v->post_code<br />Telp : $v->phone<br />\";";
                            $x++;
                        }                                                
                    }        
                }
                ?>
                                        
                var st = "";
                for (var i = 1; i <= places.length; i++) {
                    // Adding the marker as usual
                    if(i == 1) {
                        st = "1";
                    }else if(i == places.length) {
                        st = places.length;
                    }else {
                        st = i;
                    }
                    var marker = new google.maps.Marker({
                        position: places[i-1],
                        map: map,
                        title: 'Outlet ke-' + st,
                        icon: '<?=base_url()?>file/images/icongis/outlet.png'
                    });
                    

                        // Wrapping the event listener inside an anonymous function
                        // that we immediately invoke and passes the variable i to.
                    (function(i,st, marker) {
                        // Creating the event listener. It now has access to the values of
                        // i and marker as they were during its creation
                        google.maps.event.addListener(marker, 'click', function() {
                            var infowindow = new google.maps.InfoWindow({
                            content: info[i-1] + ""
                            });
                            infowindow.open(map, marker);
                             

                        });
                        
                        
                    })(i,st, marker);
                }
                
                
                
                
                
                
                
                
                
                
                
                
                //by donny
                var posmax=new google.maps.LatLng(maxlat,maxlng);
                var posmin=new google.maps.LatLng(minlat,minlng);
				var bounds= new google.maps.LatLngBounds();
                
                   google.maps.event.addListener(map, 'bounds_changed', function() {
                     if (map.getBounds().contains(posmin)==false && map.getBounds().contains(posmax)==false && got==false){
                        map.setZoom(map.getZoom()-1);                  
                     }else{
                        got=true;
                     }
                  });
                
                //------
                
                
                
                
                
                
                
                
                
                <?php
                
                
                //boundary
                $bound = "";
                if($hasil != null) {
                    
                    $tid=$this->db->query('select f_get_territory_id(\''.$this->session->userdata('username') .'\')')->row()->f_get_territory_id;
                    $ter = $this->mgis->getTerritoryMember($tid);
                    
                    if($ter != null) {
                        $i = 0;
                        
                        foreach($ter as $r) {
                            $this->mgis->pathTer = "";
                            $hal = $this->mgis->getBoundaryTerritory($r);
                            $bound = "";
                            $x = 0;
                            if($hal != null) {
                                foreach($hal as $v) {
                                    if($x <> 0) {
                                        $bound .= ",";
                                    }                       
                                    $bound .= "new google.maps.LatLng(".$v->lat.",".$v->lon.")";

                                    $x++;
                                }   
                            
                            $ret = $this->mgis->getTerritoryById($r);
                            $territory_name = $this->mgis->getParentTerritory($r);
                            //$territory_name = $ret['territory_name'];
                            $fill_color = $ret['fill_color'];
                            if($fill_color == "") {
                                $fill_color = "000000";
                            }else {
                                $fill_color = $ret['fill_color'];
                            }
                            
                            $border_color = $ret['border_color'];
                            if($border_color == "") {
                                $border_color = "000000";
                            }else {
                                $border_color = $ret['border_color'];
                            }
                            
                            ?>
                            var bound<?=$i?> = [<?= $bound ?>];               
                            // Creating the polyline object
                            var polygon<?=$i?> = new google.maps.Polygon({
                                path: bound<?=$i?>,
                                strokeColor: "#ff0000",
                                strokeOpacity: 0.7,
                                strokeWeight: 1,
                                fillColor: '#<?=$fill_color?>',
                                strokeColor: '#<?=$border_color?>'
                            });
                            // Adding the polyline to the map
                            polygon<?=$i?>.setMap(map);    
                            
                            
                           // Adding mouseover event to the polygon
                            google.maps.event.addListener(polygon<?=$i?>, 'mouseover', function(e) {
                                // Setting the color of the polygon to blue
                                polygon<?=$i?>.setOptions({
                                    fillColor: '#0000ff',
                                    strokeColor: '#0000ff'
                                });
                                
                                var vertices = this.getPath();
                                var contentString = "<b><?=$territory_name?></b><br />";

                                // Iterate over the vertices.
                                for (var i =0; i < vertices.length; i++) {
                                  var xy = vertices.getAt(i);
                                }

                                // Replace our Info Window's position
                                myInfowindow.setContent(contentString);
                                myInfowindow.setPosition(e.latLng);
                                myInfowindow.open(map);
                            });

                            // Adding mouseover event to the polygon
                            google.maps.event.addListener(polygon<?=$i?>, 'mouseout', function(e) {
                            // Setting the color of the polygon to blue
                                polygon<?=$i?>.setOptions({
                                    fillColor: '#<?=$fill_color?>',
                                    strokeColor: '#<?=$border_color?>'
                                });
                                myInfowindow.close();
                            });
                                        
                            <?php                            
                            }
                            $i++;
                        }                        
                    }                                                                
                }
                ?>       
                               
                };
                //ibCallbacks();
                
                })();
        </script>
        
<div id="map" style="width:98%;height:700px;margin:10px;border:1px solid #000000;"></div>
</div>